package com.dna.common.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketImpl;
import java.util.ArrayList;
import java.util.List;

import com.dna.common.io.MultiStreamJack;
import com.dna.common.io.StreamJack;

public class PlugableSocket extends Socket {

	private MultiStreamJack input;
	private MultiStreamJack output;
	
	private List<InputStream> tempInputs = new ArrayList<InputStream>();
	private List<OutputStream> tempOutputs = new ArrayList<OutputStream>();
	
	public PlugableSocket() {
		super();
	}
	
	public PlugableSocket(String hostname, int port) throws IOException {
		super(hostname, port);
	}
	
	public PlugableSocket(SocketImpl socketImpl) throws SocketException {
		super(socketImpl);
	}
	
	public PlugableSocket(Proxy proxy) {
		super(proxy);
	}
	
	public PlugableSocket(InetAddress inetAddress, int port) throws IOException {
		super(inetAddress, port);
	}
	
	protected void init() throws IOException {
		input = new MultiStreamJack(StreamJack.DEFAULT_BUFFER_SIZE, tempInputs.toArray(new InputStream[tempInputs.size()]), this.getOutputStream());
		output = new MultiStreamJack(StreamJack.DEFAULT_BUFFER_SIZE, new InputStream[]{this.getInputStream()}, tempOutputs.toArray(new OutputStream[tempOutputs.size()]));
		input.autoFlush(true);
		output.autoFlush(true);
		input.start();
		output.start();
	}
	
	@Override
	public void connect(SocketAddress address, int port) throws IOException {
		super.connect(address, port);
		init();
		
	}
	
	public boolean addInput(InputStream inputStream) {
		if(input==null)
			return tempInputs.add(inputStream);
		return input.addInput(inputStream);
	}
	
	public boolean addOutput(OutputStream outputStream) {
		if(output==null)
			return tempOutputs.add(outputStream);
		return output.addOutput(outputStream);
	}
}
